package com.bai.translation;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CodeReplacer {

    private static final String JAVA_EXTENSION = ".java";
    private static final Pattern VALIDATION_MESSAGE_PATTERN = Pattern.compile("message\\s*=\\s*\"([^\"]*[\\u4e00-\\u9fa5][^\"]*)\"");
    private static final Pattern EXCEPTIONS_TR_PATTERN = Pattern.compile("Exceptions\\.tr\\(\\s*[^,]+,\\s*\"([^\"]*[\\u4e00-\\u9fa5][^\"]*)\"\\)");

    public static void replaceChineseInAnnotationsAndMethods(String codeBaseDir, Map<String, String> translations, Map<String, String> md5Map, List<String> untranslated) throws IOException {
        Files.walk(Paths.get(codeBaseDir))
                .filter(Files::isRegularFile)
                .filter(path -> path.toString().endsWith(JAVA_EXTENSION))
                .forEach(path -> {
                    try {
                        // 使用 BufferedReader 读取所有行，包括末尾的换行符
                        List<String> lines = new ArrayList<>();
                        try (BufferedReader reader = Files.newBufferedReader(path)) {
                            String line;
                            while ((line = reader.readLine()) != null) {
                                lines.add(line);
                            }
                        }

                        // 检查原文件是否以换行符结尾
                        boolean endsWithNewline = false;
                        try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r")) {
                            file.seek(file.length() - 1);
                            int lastByte = file.read();
                            if (lastByte == '\n') {
                                endsWithNewline = true;
                            }
                        }
                        List<String> newLines = new ArrayList<>(16);

                        for (String line : lines) {
                            line = replaceValidationMessages(line, translations, md5Map, untranslated);
                            line = replaceExceptionsTr(line, translations, md5Map, untranslated);
                            newLines.add(line);
                        }
                        // 手动处理换行符，确保没有额外的空行
                        StringBuilder contentBuilder = new StringBuilder();
                        for (String line : newLines) {
                            contentBuilder.append(line).append(System.lineSeparator());
                        }

                        // 如果原文件以换行符结尾，则保持换行符
                        if (!endsWithNewline && contentBuilder.length() > 0) {
                            contentBuilder.setLength(contentBuilder.length() - System.lineSeparator().length());
                        }

                        String content = contentBuilder.toString();

                        // 写入文件
                        Files.write(path, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }

    private static String replaceValidationMessages(String line, Map<String, String> translations, Map<String, String> md5Map, List<String> untranslated) {
        Matcher matcher = VALIDATION_MESSAGE_PATTERN.matcher(line);
        while (matcher.find()) {
            String chineseMessage = matcher.group(1);
            String translation = translations.get(chineseMessage);
            if (translation != null) {
                String md5Key = MD5Util.md5(chineseMessage);
                md5Map.putIfAbsent(md5Key, chineseMessage);
                line = line.replace(chineseMessage, "{i18n." + md5Key + "}");
            } else {
                untranslated.add(chineseMessage);
            }
        }
        return line;
    }

    private static String replaceExceptionsTr(String line, Map<String, String> translations, Map<String, String> md5Map, List<String> untranslated) {
        Matcher matcher = EXCEPTIONS_TR_PATTERN.matcher(line);
        while (matcher.find()) {
            String chineseMessage = matcher.group(1);
            String translation = translations.get(chineseMessage);
            if (translation != null) {
                String md5Key = MD5Util.md5(chineseMessage);
                md5Map.putIfAbsent(md5Key, chineseMessage);
                line = line.replace(chineseMessage, "i18n." + md5Key);
            } else {
                untranslated.add(chineseMessage);
            }
        }
        return line;
    }
}
